#include "mainwindow.h"
#include "ui_mainwindow.h"

#include <QVBoxLayout>
#include <QPushButton>
#include <QLabel>
#include <QString>
#include <QDebug>
#include <QFileDialog>
#include <QBuffer>

const char *key = "hello";

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    QSharedMemory *shMe = new QSharedMemory(key,this);
    //QVBoxLayout *layout = new QVBoxLayout(this);

    QWidget *mainWidget = new QWidget(this);
    QVBoxLayout *layout = new QVBoxLayout(mainWidget);
    setCentralWidget(mainWidget);

    QPushButton *saveButton = new QPushButton(tr("Save"),this);
    layout->addWidget(saveButton);
    QLabel *picLabel = new QLabel(this);
    layout->addWidget(picLabel);
    QPushButton *loadButton = new QPushButton(tr("Load"),this);
    layout->addWidget(loadButton);

    connect(saveButton,&QPushButton::clicked,this,[=]()
    {
        //检测程序当前是否关联共享内存
        if (shMe->isAttached()){
            //解除关联
            shMe->detach();
        }
        //Qt 打开文件的默认路径
//        QString filename = QFileDialog::getOpenFileName(this);
//        QPixmap pixmp(filename);
//        picLabel->setPixmap(pixmp);

        QString data = "hello";
        QBuffer buffer;
        //声明QBuffer的实例buffer为存储缓冲区
        QDataStream out(&buffer);
        buffer.open(QBuffer::ReadWrite);
        //out << pixmp;
        out << data;
        int size = buffer.size();
        if (!shMe->create(size)){
            qDebug() << tr("create error:") << shMe->errorString();
        } else {
            shMe->lock();
            char *to = static_cast<char *>(shMe->data());
            const char * from = buffer.data().constData();
            memcpy(to,from,qMin(size,shMe->size()));
            shMe->unlock();
        }
    });

    connect(loadButton,&QPushButton::clicked,this,[=]()
    {
        if (shMe->error() != QSharedMemory::NoError){
            qDebug() << tr("Attach Error") << shMe->errorString();
        } else {
            QBuffer buffer;
            QDataStream in(&buffer);
            //QPixmap pixmp;
            shMe->lock();
            QString data;
            buffer.setData(static_cast<const char *>(shMe->constData()),shMe->size());
            buffer.open(QBuffer::ReadWrite);
            //qDebug() << "hello";
            in >> data;
            shMe->unlock();
            shMe->detach();
            //picLabel->setPixmap(pixmp);
            picLabel->setText(data);
        }

    });


}

MainWindow::~MainWindow()
{
    delete ui;
}
